package com.example.demo.service.impl;

import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.dto.StudentRequestDTO;
import com.example.demo.controller.bean.Result;
import com.example.demo.mapper.StudentManageMapper;
import com.example.demo.mapper.entity.Student;
import com.example.demo.mapper.entity.StudentView;
import com.example.demo.service.StudentManageService;

import com.example.demo.utils.PageBo;
import com.example.demo.utils.PageVo;

import com.example.demo.utils.MD5Util;

import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


@Service
public class StudentManageServiceImpl extends ServiceImpl<StudentManageMapper, Student> implements StudentManageService {

    @Autowired
    private StudentManageMapper mapper;

    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public static final Integer N_Thread = Runtime.getRuntime().availableProcessors() * 2 + 1;

    @Override
    public PageVo<StudentView> getStudentList(PageBo pageBo) {
        //  int schoolId = mapper.getSchoolId(stkaaaId);
        // List<Student> list = mapper.getStudentListById(schoolId);
        List<StudentView> logs = mapper.getStudentList();
        return new PageVo<>(pageBo, logs);
    }

   @Override
    public PageVo<StudentView> searchStudent(String studentNum, String name,String college,String major,PageBo pageBo) {
        StudentView example=new StudentView();
        example.setNumber(studentNum);
        example.setName(name);
        example.setCollegeName(college);
        example.setMajorName(major);

        List<StudentView> list = mapper.searchByExample(example);

        return new PageVo<>(pageBo, list);
    }
 /*
    @Override
    public PageVo<StudentView> searchStudent(String studentNum, String name, String college, String major, PageBo pageBo) {
        //  int schoolId = mapper.getSchoolId(stkaaaId);
        // List<Student> list = mapper.getStudentListById(schoolId);
        List<StudentView> list = mapper.getStudentList();
        //按照学号，籍贯，民族，学院，专业，宿舍楼
        list = list.stream()
                .filter(o ->
                        (studentNum == null || o.getNumber().contains(studentNum)) &&
                                (name == null || o.getNativePlace().contains(name)) &&
                                (college == null || o.getCollegeName().contains(college)) &&
                                (major == null || o.getMajorName().contains(major)))
                .collect(Collectors.toList());

        return new PageVo<>(pageBo, list);
    }*/

    @Override
    public Result<String> deleteStudent(StudentView student) {
        String studentNumber = student.getNumber();
        if(studentNumber!=null){
            mapper.deleteStudent(studentNumber);
            return Result.ok("删除成功");
        }else{
            return Result.error(400, "删除失败");
        }
    }

    @Override
    public Result<String> updateStudent(StudentRequestDTO request, String college, String major) {
        Student newStudent=setStudent(request);

        Integer collegeId=mapper.selectCollege(college);
        Integer majorId=mapper.selectMajor(major);

        if((college!=null&&major!=null)||(college==null&&major!=null)|(college!=null&&major==null)){
            if(collegeId != null && majorId != null){
                newStudent.setMajorId(majorId);
                newStudent.setCollegeId(collegeId);
                mapper.updateById(newStudent);
                return Result.ok("修改成功");
            } else if (collegeId == null) {
                return Result.error(400, "修改失败，学院不存在");
            } else if (majorId == null) {
                return Result.error(400, "修改失败，专业不存在");
            } else {
                return Result.error(400, "修改失败，学院和专业都不存在");
            }
        }else {
            mapper.updateById(newStudent);
            return Result.ok("修改成功");
        }
    }
    @Override
    public Student addStudent(StudentRequestDTO request, String college, String major) {
        Student newStudent=setStudent(request);

        Integer collegeId=mapper.selectCollege(college);
        Integer majorId=mapper.selectMajor(major);
        if((college!=null && major==null)|| (college==null&&major!=null)||(college==null&&major==null)){
            if (collegeId != null && majorId != null) {
                newStudent.setMajorId(majorId);
                newStudent.setCollegeId(collegeId);
                mapper.addStudent(newStudent);
            } else if (collegeId == null) {
                SaResult.error();
            } else if (majorId == null) {
                SaResult.error();
            } else {
                SaResult.error();
            }
        } else {
            mapper.addStudent(newStudent);
        }
        return newStudent;
    }

    @Override
    public void deleteList(List<StudentView> studentList) {
        // 遍历 userList 并输出每个元素
        for (StudentView user : studentList) {
            System.out.println(user);
        }
        mapper.deleteStudentList(studentList);
    }

    @Override
    public void saveData(List<Student> studentList) {
        this.saveBatch(studentList);
    }

    //多线程导入数据库
    @Override
    public void csvImportAsync(MultipartFile file) {
        List<Student> studentList = convertCsvToList(file);

        for (Student student : studentList) {
            // 根据number查询数据库
           /* QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("number", student.getNumber());
            Student existingStudent = mapper.selectOne(queryWrapper);*/

            Student existingStudent = mapper.selectStudentByNumber(student.getNumber());

            if (existingStudent != null) {
                // 如果存在，则执行更新操作
                student.setId(existingStudent.getId()); // 设置ID
               // mapper.updateById(student); // 更新数据
                mapper.updateStudent(student);
            } else {
                // 如果不存在，则执行插入操作
                String initialPassword = "abc123";
                student.setPassword(MD5Util.encryptPassword(initialPassword)); // 直接设置密码，无需forEach
                student.setState(1);
                mapper.addStudent(student); // 插入数据
            }
        }
    }


    private List<Student> convertCsvToList (MultipartFile file){
        HeaderColumnNameMappingStrategy<Student> mappingStrategy  = new HeaderColumnNameMappingStrategy<>();
        mappingStrategy.setType(Student.class);
        CsvToBean<Student> build = null;
        try {
            build = new CsvToBeanBuilder<Student>(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8)).withMappingStrategy(mappingStrategy).withSeparator(',').build();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        List<Student> studentList = build.parse();
        return studentList;
    }

    private Student setStudent(StudentRequestDTO request) {
        Student student = new Student();
        student.setId(request.getId());
        student.setNumber(request.getNumber());
        student.setName(request.getName());
        student.setGender(request.getGender());

        if (request.getBirthday()!=null&&request.getBirthday().matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{3}Z")) {
            // 如果日期格式为 "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
            LocalDateTime birthday = LocalDateTime.parse(request.getBirthday(), inputFormatter);
            LocalDateTime birthdayPlusOneDay = birthday.plusDays(1);
            student.setBirthday(birthdayPlusOneDay.format(outputFormatter));
        } else if (request.getBirthday()!=null&&request.getBirthday().matches("\\d{4}-\\d{2}-\\d{2}")) {
            // 如果日期格式已经是 "yyyy-MM-dd"
            // 直接设置生日，无需加一天，因为这里假设已经是对的日期格式
            student.setBirthday(request.getBirthday());
        } else if (request.getBirthday()==null) {
            student.setBirthday(null);
        }else {
            // 日期格式不正确时的错误处理
            throw new IllegalArgumentException("Invalid date format for birthday");
        }

        student.setIdentityCard(request.getIdentityCard());
        student.setNativePlace(request.getNativePlace());
        student.setNationality(request.getNationality());
        student.setPoliticsStatus(request.getPoliticsStatus());
        student.setPhone(request.getPhone());
        student.setEmail(request.getEmail());
        student.setClazz(request.getClazz());
        student.setDormitory(request.getDormitory());
        student.setRoomNumber(request.getRoomNumber());
        student.setBedNumber(request.getBedNumber());
        student.setContact(request.getContact());
        student.setContactPhone(request.getContactPhone());
        student.setScore(request.getScore());
        student.setState(request.getState());

        return student;
    }




}
